﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.BackgroundAudio;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.IO;
using Microsoft.Phone.Shell;
using Coding4Fun.Phone.Controls;

namespace XiaMiRingtone
{
    public partial class MainPage : PhoneApplicationPage
    {
        System.Windows.Threading.DispatcherTimer myDispatcherTimer = new System.Windows.Threading.DispatcherTimer();
        string fname;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            SetSkin();
            BackgroundAudioPlayer.Instance.PlayStateChanged += new EventHandler(Instance_PlayStateChanged);
            if (null != BackgroundAudioPlayer.Instance.Track)
            {
                //BackgroundAudioPlayer.Instance.Volume = 1;
                BackgroundAudioPlayer.Instance.Play();
                SetUI();
            }
   
        }

        void Instance_PlayStateChanged(object sender, EventArgs e)
        {
            try
            {
                BackgroundAudioPlayer.Instance.Volume = 1;
                if (BackgroundAudioPlayer.Instance.Track != null)
                {
                    SetUI();
                    sTime.Value = (int)BackgroundAudioPlayer.Instance.Position.TotalSeconds;
                }
            }
            catch
            { }

            switch (BackgroundAudioPlayer.Instance.PlayerState)
            {
                case PlayState.Playing:
                    break;
                case PlayState.Paused:
                    break;
                case PlayState.Stopped:
                    break;
                case PlayState.Error:
                    break;
            }
            StartTimer();
            
            

        }

        private void SetSkin()
        {
            var store = IsolatedStorageFile.GetUserStoreForApplication();
            if (store.FileExists("skin.jpg"))
            {
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("skin.jpg", FileMode.Open, store))
                {
                    if (stream.Length > 10000)
                    {
                        BitmapImage bi = new BitmapImage();
                        bi.SetSource(stream);
                        Ib.ImageSource = bi;
                    }
                }
            }
        }

        public void StartTimer()
        {
            myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000);
            myDispatcherTimer.Tick += new EventHandler(Each_Tick);
            myDispatcherTimer.Start();// A variable to count with.

        }

        public void Each_Tick(object o, EventArgs sender)
        {

            try
            {
                if (BackgroundAudioPlayer.Instance.Track != null)
                {
                    if (tbSonger.Text != BackgroundAudioPlayer.Instance.Track.Artist)
                    {
                        SetUI();
                    }

                    try
                    {
                        sTime.Value = (int)BackgroundAudioPlayer.Instance.Position.TotalSeconds;
                        tbTime.Text = BackgroundAudioPlayer.Instance.Position.ToString(@"mm\:ss");
                    }
                    catch
                    {

                    }
                }
            }
            catch { }
            
        }

        private void SetImage(string url)
        {
            BitmapImage bmp = new BitmapImage();
            bmp.UriSource = new Uri(url);
            iAlbumImage.Source = bmp;
        }

        private void SetUI()
        {
            tbSongName.Text = BackgroundAudioPlayer.Instance.Track.Title;
            tbSonger.Text = BackgroundAudioPlayer.Instance.Track.Artist;
            
            SetImage(BackgroundAudioPlayer.Instance.Track.Album);
            sTime.Maximum = (int)BackgroundAudioPlayer.Instance.Track.Duration.TotalSeconds;
            if (BackgroundAudioPlayer.Instance.Track != null)
            {
                sTime.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                sTime.Visibility = System.Windows.Visibility.Collapsed;
            }
            
            try
            {
                sTime.Value = (int)BackgroundAudioPlayer.Instance.Position.TotalSeconds;
                tbTime.Text = BackgroundAudioPlayer.Instance.Position.ToString(@"mm\:ss");
            }
            catch
            {

            }
        }

        public void DownloadSong()
        {
            var store = IsolatedStorageFile.GetUserStoreForApplication();
            Uri durl = BackgroundAudioPlayer.Instance.Track.Source;
            fname = BackgroundAudioPlayer.Instance.Track.Title + ".mp3";

            if (store.FileExists(fname))
            {
                store.DeleteFile(fname);
            }

            WebClient wc = new WebClient();
            wc.OpenReadAsync(durl);
            wc.DownloadProgressChanged += (senderm, e) =>
            {
                slider1.Visibility = System.Windows.Visibility.Visible;
                slider1.Value = e.ProgressPercentage;
                if (e.ProgressPercentage == 100)
                {
                    slider1.Visibility = System.Windows.Visibility.Collapsed;
                    Download_Toast();
                }
            };
            wc.OpenReadCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    using (var filestream = new IsolatedStorageFileStream(fname, FileMode.Create, store))
                    {
                        int i;
                        var buffer = new byte[10000];
                        while ((i = e.Result.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            filestream.Write(buffer, 0, i);
                        }
                        filestream.Seek(0, SeekOrigin.Begin);
                    }
                }
                else
                {
                    MessageBox.Show(e.Error.ToString());
                }
            };
        }

        private void Download_Toast()
        {
            ToastPrompt toast = new ToastPrompt(); //实例化 

            //toast.Title = "ToastPrompt"; //设置标题 
            toast.Message ="《"+fname+"》"+ "下载完成!"; //设置正文消息 
            //toast.FontSize = 50; //设置文本大小(可选) 
            toast.TextOrientation = System.Windows.Controls.Orientation.Horizontal; //设置呈现为纵向 
            //toast.ImageSource = new BitmapImage(new Uri("ApplicationIcon.png", UriKind.RelativeOrAbsolute));    //设置 标题前的图片(可选) 

            toast.Completed += toast_Completed; //Toast显示完毕后触发事件(可选) 
            toast.Show(); 
        }

        void toast_Completed(object sender, PopUpEventArgs<string, PopUpResult> e)
        {
            //TODO:Toast显示完毕后事件处理 
        }

        #region override
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            SetSkin();
            try
            {

                    BackgroundAudioPlayer.Instance.Play();
                    SetUI();
                    myDispatcherTimer.Start();
                    
                
            }
            catch 
            {
                BackgroundAudioPlayer.Instance.SkipNext();
            }
            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            myDispatcherTimer.Stop();
            base.OnNavigatedFrom(e);
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            MessageBoxResult mb = MessageBox.Show("确定退出？", "退出", MessageBoxButton.OKCancel);
            if (mb != MessageBoxResult.OK)
            {
                e.Cancel = true;
            }
            myDispatcherTimer.Stop();
            BackgroundAudioPlayer.Instance.Close();
        }
        #endregion override

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            //BackgroundAudioPlayer.Instance.SkipNext();
        }

        

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            DownloadSong();
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            BackgroundAudioPlayer.Instance.SkipNext();
        }

        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/lingyin.xaml", UriKind.Relative));
        }

        private void ApplicationBarMenuItem_Click_1(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/setting.xaml", UriKind.Relative));
        }

        private void ApplicationBarMenuItem_Click_2(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/about.xaml", UriKind.Relative));
        }
    }
}